package com.exampl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exampl.common.CustomException;
import com.exampl.dao.CategoryDao;
import com.exampl.domain.Category;
import com.exampl.domain.Dish;
import com.exampl.domain.Setmeal;
import com.exampl.service.CategoryService;
import com.exampl.service.DishService;
import com.exampl.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService{

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    DishService dishService;

    @Autowired
    SetmealService setmealService;

    @Override
    public IPage<Category> getPage(Integer page, Integer pageSize) {
        IPage<Category> iPage = new Page<Category>(page, pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<Category>();
        lqw.orderByAsc(Category::getSort);
        categoryDao.selectPage(iPage, lqw);
        return iPage;
    }

    @Override
    public void remove(Long id) {
        // 判断该分类中是否存在菜品
        LambdaQueryWrapper<Dish> dishLqw = new LambdaQueryWrapper<Dish>();
        dishLqw.eq(Dish::getCategoryId, id);
        int count1 = dishService.count(dishLqw);
        if(count1 > 0){
            // 该分类中存在菜品，抛出异常
            throw new CustomException("该分类中存在菜品，无法删除！");
        }

        // 判断该分类中是否存在套餐
        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<Setmeal>();
        setmealLqw.eq(Setmeal::getCategoryId, id);
        int count2 = setmealService.count(setmealLqw);
        if(count2 > 0){
            // 该分类中存在套餐，抛出异常
            throw new CustomException("该分类中存在套餐，无法删除！");
        }

        // 直接删除
        super.removeById(id);
    }

    @Override
    public Category FindByName(String name) {
        return categoryDao.FindByName(name);
    }

    @Override
    public void updateDelete(Long id) {
        categoryDao.updateDelete(id);
    }
}
